<template>
    <div class="backTop rounded-circle" ref="backTop" @click="backTop()">
        <img src="@/assets/images/top.png" height="40">
    </div>
</template>

<script>
export default {
    methods: {
        backTop() {
            // 返回速度
            let backSpead = 0;
            // 定时器，每20ms循环一次
            let mInter = setInterval(() => {
                // 速度不断增加
                backSpead += 32;
                // 如果距离减速度等于负数则直接设置scrollTop = 0
                if( document.documentElement.scrollTop - backSpead < 0 && document.body.scrollTop - backSpead < 0){
                    document.documentElement.scrollTop = document.body.scrollTop = 0;
                    clearInterval(mInter);
                }
                else {
                    document.documentElement.scrollTop ? document.documentElement.scrollTop -= backSpead : document.body.scrollTop -= backSpead;
                }
            }, 20)
        },
        isShow() {
            if(document.documentElement.scrollTop >= 310 || document.body.scrollTop >= 310) {
                this.$refs.backTop.style.opacity = "1";
            }
            else {
                this.$refs.backTop.style.opacity = "0";
            }
        }
    },
    mounted() {
        // 监听滚轮
        window.addEventListener("scroll", this.isShow);
    },
    beforeDestroy() {
        // 销毁
        window.removeEventListener("scroll", this.isShow);
    },
}
</script>

<style lang="stylus" scoped>
.backTop
    opacity 0
    position fixed
    right $float_button_right
    bottom $float_button_bottom2
    width $float_button_width
    height $float_button_height
    text-align center
    transition .2s
    cursor pointer
    background-color #fff
    img:hover
        transform scale(1.2)

</style>